package com.micolor.logr.runtime.component;


import com.micolor.logr.runtime.annotation.LogComponent;
import com.micolor.logr.runtime.annotation.LogField;
import com.micolor.logr.runtime.annotation.LogRecord;
import com.micolor.logr.runtime.entity.FieldDetail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @BelongsProject: demo-collection
 * @BelongsPackage: com.micolor.annotationdemo.log.component
 * @Author: Evan.Ge
 * @CreateTime: 2024-07-05  15:06
 * @Description: 用来处理LogField和LogComponent注解的工具类
 * @Version: 1.0
 */
@Service
@Slf4j
public class AnnotationOperateComponent {
    /**
     * 用于处理LogComponent注解的的方法
     * @param logRecord LogRecord注解记录
     * @return  注解组件名称
     * @throws Exception 当实体没有使用LogComponent注解时抛出异常
     */
    public LogComponent getLogComponentValue(LogRecord logRecord) throws Exception {
        LogComponent logComponent = logRecord.entity().getAnnotation(LogComponent.class);
        //如果类没有配置LogComponent注解，则抛出异常
        if(logComponent==null){
            throw new Exception("annotation 'LogComponent' not in "+logRecord.entity().getName()+"，use @LogComponent for the class .");
        }
        log.debug("logComponent==>{}",logComponent);
        return logComponent;
    }

    /**
     * 用于处理LogField注解的的方法
     * @param logRecord LogRecord注解记录
     * @return 添加了LogField注解的字段的注解信息和字段信息
     */
    public List<FieldDetail> getLogFields(LogRecord logRecord) {
        List<FieldDetail> list = new ArrayList<>();

        List<Field> fieldList = new ArrayList<>();
        fieldList.addAll(Arrays.asList(logRecord.entity().getDeclaredFields()));
        fieldList.addAll(Arrays.asList(logRecord.entity().getSuperclass().getDeclaredFields()));

        for (Field field : fieldList) {
            FieldDetail fieldDetail = new FieldDetail();
            fieldDetail.setFieldName(field.getName());
            if (field.isAnnotationPresent(LogField.class)) {
                LogField logField = field.getAnnotation(LogField.class);
                fieldDetail.setLogField(logField);
            }
            list.add(fieldDetail);
        }
        return list;
    }
}
